package cn.edu.gznu.wecampus.core.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.gznu.wecampus.core.BusinessException;
import cn.edu.gznu.wecampus.core.common.entity.jpa.User;
import cn.edu.gznu.wecampus.core.common.repository.jpa.UserRepository;
import cn.edu.gznu.wecampus.core.utils.JwtUtils;
import cn.edu.gznu.wecampus.core.web.RestResponse;
import cn.edu.gznu.wecampus.core.web.RestResponseElement;
import cn.edu.gznu.wecampus.core.weixin.service.TicketService;
import cn.edu.gznu.wecampus.core.weixin.service.UserInfoService;
import cn.edu.gznu.wisedu.entity.ldap.Member;
import cn.edu.gznu.wisedu.repository.ldap.MemberRepository;

@RestController
@RequestMapping("/api/weixin")
public class WeixinApi {
	
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private MemberRepository memberRepository;
	
	@Autowired
	private TicketService ticketService;
	
	@Autowired
	private UserInfoService userInfoService;
	
	@RequestMapping("jwt")
	public RestResponse jwt(String code) {
		RestResponseElement response = new RestResponseElement();
		String userId = userInfoService.get(code).getUserId();
		Member member = memberRepository.findByXgh(userId);
		if(member != null) {
			String jwtToken = JwtUtils.sign(member.getUid());
			AuthVo vo = new AuthVo();
			vo.setXgh(member.getUid());
			vo.setName(member.getCommonName());
			vo.setJwtToken(jwtToken);
			vo.setWeixinTicket(ticketService.getEntity().getTicket());
			response.setElement(vo);
			return response;
		}
		User user = userRepository.findByUsername(userId);
		if(user != null) {
			String jwtToken = JwtUtils.sign(user.getUsername());
			AuthVo vo = new AuthVo();
			vo.setXgh(user.getUsername());
			vo.setName(user.getRealname());
			vo.setJwtToken(jwtToken);
			vo.setWeixinTicket(ticketService.getEntity().getTicket());
			response.setElement(vo);
			return response;
		}
		throw new BusinessException("认证失败！请加入贵师微校园！");
	}
}
